package com.ruoyi.toobit.service;

import com.ruoyi.common.config.TooBitApiConfig;
import com.ruoyi.util.ApiAuthenticationUtils;
import com.ruoyi.util.ApiAuthenticationUtils.AuthType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.TreeMap;

/**
 * TooBit API服务类
 * 提供带验签的API调用方法
 * 
 * @author TooBit
 * @date 2025-01-06
 */
@Service
public class TooBitApiService {
    
    private static final Logger log = LoggerFactory.getLogger(TooBitApiService.class);
    
    @Autowired
    private TooBitApiConfig apiConfig;
    
    /**
     * 验签请求 exchangeInfo 接口
     * 获取交易所交易对信息
     * 
     * @return API响应结果，失败时返回null
     */
    public String getExchangeInfoWithSignature() {
        log.info("🚀 开始验签请求 TooBit exchangeInfo 接口");
        
        try {
            // 创建API配置
            ApiAuthenticationUtils.ApiConfig config = new ApiAuthenticationUtils.ApiConfig(
                apiConfig.getBaseUrl(),
                apiConfig.getAccessKey(), 
                apiConfig.getSecretKey()
            );
            config.setRecvWindow(apiConfig.getRecvWindow());
            
            // 记录开始时间
            long startTime = System.currentTimeMillis();
            
            // 发送带验签的请求 (使用MARKET_DATA类型，需要API Key但无需签名)
            String response = ApiAuthenticationUtils.sendAuthenticatedGet(
                config, 
                "/api/v1/exchangeInfo", 
                null, 
                AuthType.MARKET_DATA
            );
            
            long endTime = System.currentTimeMillis();
            long responseTime = endTime - startTime;
            
            if (response != null && !response.isEmpty()) {
                // 分析响应数据
                int symbolCount = countOccurrences(response, "\"symbol\":");
                int responseLength = response.length();
                
                log.info("✅ TooBit API请求成功!");
                log.info("📊 响应时间: {}ms", responseTime);
                log.info("📏 响应长度: {} 字符", responseLength);
                log.info("🏪 交易对数量: {} 个", symbolCount);
                
                // 验证关键字段
                if (response.contains("symbols") && response.contains("serverTime")) {
                    log.info("🔍 数据验证: 包含必需字段 (symbols, serverTime)");
                } else {
                    log.warn("⚠️ 数据验证: 缺少部分必需字段");
                }
                
                return response;
                
            } else {
                log.error("❌ TooBit API请求失败: 无响应数据");
                return null;
            }
            
        } catch (Exception e) {
            log.error("🚨 TooBit API请求异常: {}", e.getMessage(), e);
            return null;
        }
    }
    
    /**
     * 验签请求 exchangeInfo 接口 (完整签名版本)
     * 使用USER_DATA类型，包含完整的HMAC SHA256签名
     * 
     * @return API响应结果，失败时返回null
     */
    public String getExchangeInfoWithFullSignature() {
        log.info("🔐 开始完整验签请求 TooBit exchangeInfo 接口");
        
        try {
            // 创建API配置
            ApiAuthenticationUtils.ApiConfig config = new ApiAuthenticationUtils.ApiConfig(
                apiConfig.getBaseUrl(),
                apiConfig.getAccessKey(), 
                apiConfig.getSecretKey()
            );
            config.setRecvWindow(apiConfig.getRecvWindow());
            
            // 记录开始时间
            long startTime = System.currentTimeMillis();
            
            // 发送带完整签名的请求
            String response = ApiAuthenticationUtils.sendAuthenticatedGet(
                config, 
                "/api/v1/exchangeInfo", 
                null, 
                AuthType.USER_DATA
            );
            
            long endTime = System.currentTimeMillis();
            long responseTime = endTime - startTime;
            
            if (response != null && !response.isEmpty()) {
                // 分析响应数据
                int symbolCount = countOccurrences(response, "\"symbol\":");
                int responseLength = response.length();
                
                log.info("✅ TooBit API完整验签请求成功!");
                log.info("📊 响应时间: {}ms", responseTime);
                log.info("📏 响应长度: {} 字符", responseLength);
                log.info("🏪 交易对数量: {} 个", symbolCount);
                log.info("🔐 HMAC SHA256签名验证: 通过");
                
                return response;
                
            } else {
                log.error("❌ TooBit API完整验签请求失败: 无响应数据");
                return null;
            }
            
        } catch (Exception e) {
            log.error("🚨 TooBit API完整验签请求异常: {}", e.getMessage(), e);
            return null;
        }
    }
    
    /**
     * 批量获取特定交易对信息
     * 从exchangeInfo响应中提取指定交易对的详细信息
     * 
     * @param symbols 要查询的交易对列表
     * @return 交易对信息Map，key为交易对名称，value为交易对详细信息
     */
    public Map<String, Object> getSpecificSymbolsInfo(String[] symbols) {
        log.info("📋 获取指定交易对信息: {}", String.join(", ", symbols));
        
        Map<String, Object> result = new TreeMap<>();
        
        try {
            String exchangeInfo = getExchangeInfoWithSignature();
            if (exchangeInfo != null) {
                // 这里可以解析JSON并提取特定交易对信息
                // 为了简化，先返回基本统计信息
                result.put("totalSymbols", countOccurrences(exchangeInfo, "\"symbol\":"));
                result.put("requestTime", System.currentTimeMillis());
                result.put("dataLength", exchangeInfo.length());
                result.put("requestedSymbols", symbols);
                result.put("status", "success");
                
                log.info("📊 已获取 {} 个交易对的信息", symbols.length);
            } else {
                result.put("status", "failed");
                result.put("error", "API请求失败");
            }
            
        } catch (Exception e) {
            log.error("🚨 获取交易对信息异常: {}", e.getMessage(), e);
            result.put("status", "error");
            result.put("error", e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 验证API连接状态
     * 
     * @return 连接状态信息
     */
    public Map<String, Object> validateApiConnection() {
        log.info("🔍 验证 TooBit API 连接状态");
        
        Map<String, Object> result = new TreeMap<>();
        long startTime = System.currentTimeMillis();
        
        try {
            String response = getExchangeInfoWithSignature();
            long endTime = System.currentTimeMillis();
            
            if (response != null) {
                result.put("status", "connected");
                result.put("responseTime", endTime - startTime);
                result.put("symbolCount", countOccurrences(response, "\"symbol\":"));
                result.put("dataSize", response.length());
                result.put("timestamp", endTime);
                
                log.info("✅ TooBit API连接正常");
            } else {
                result.put("status", "disconnected");
                result.put("error", "API响应为空");
                result.put("timestamp", endTime);
                
                log.warn("⚠️ TooBit API连接异常");
            }
            
        } catch (Exception e) {
            long endTime = System.currentTimeMillis();
            result.put("status", "error");
            result.put("error", e.getMessage());
            result.put("timestamp", endTime);
            
            log.error("🚨 TooBit API连接验证失败: {}", e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 计算字符串中指定子串的出现次数
     */
    private int countOccurrences(String text, String pattern) {
        if (text == null || pattern == null) {
            return 0;
        }
        
        int count = 0;
        int index = 0;
        while ((index = text.indexOf(pattern, index)) != -1) {
            count++;
            index += pattern.length();
        }
        return count;
    }
}